package com.baichang.taoshunda.dao.impl;

import com.baichang.framework.excelption.DBException;
import org.springframework.stereotype.Repository;

import com.baichang.framework.dao.impl.BaseDaoImpl;
import com.baichang.taoshunda.dao.AddressDao;
import com.baichang.taoshunda.entity.Address;

import java.util.List;
import java.util.Map;

@Repository
public class AddressDaoImpl extends BaseDaoImpl<Address> implements AddressDao {
    /**
     * 查询用户地址
     *
     * @param userId 用户编号
     * @return
     */
    @Override
    public List<Map<String, Object>> getAddressList(int userId) {
        String sql = "SELECT ad.id, ad.user_id, ad.`name`,ad.house_number,ad.city_id,ad.area_id, ad.telephone,ad.area, ad.address , ad.is_default, ad.state, ad.ulng, ad.ulat FROM t_address ad WHERE user_id = ? AND state = 1";
        sql += " ORDER BY ad.is_default DESC,ad.id DESC";
        return queryForMapList(sql, userId);
    }

    @Override
    public boolean editDeliverAddressIsNoDefalut(int userId) throws DBException {
        String sql = " UPDATE {table} SET is_default=0 where user_id=? ";
        return update(sql, userId) > 0;
    }

    /**
     * 修改为删除状态
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteDeliveryAddressById(Long id) {
        String sql = "UPDATE `t_address` SET `state`='0' WHERE (`id`=?)";
        return update(sql, id) > 0;
    }

    /**
     * 修改对应的地址为默认状态
     *
     * @param id 地址编号
     * @return
     */
    @Override
    public boolean updateDefaultAddress(Integer id) {
        String sql = " UPDATE {table} SET is_default=1 where id=? ";
        return update(sql, id) > 0;
    }

    /**
     * 获取默认地址
     *
     * @param userId 用户编号
     * @return
     */
    @Override
    public Map<String, Object> getDefaultAddress(Integer userId) {
        String sql = "SELECT * FROM t_address WHERE user_id=? and state=1 and is_default=1";
        return queryForMap(sql, userId);
    }

    /**
     * 修改用户地址
     *
     * @param userId      用户编号
     * @param address     详细地址
     * @param isDefault   是否默认   1 默认  0不是默认
     * @param name        收货人
     * @param telephone   手机号
     * @param area        地区
     * @param id          地址编号
     * @param houseNumber
     * @param ulng
     * @param ulat        @return
     * @param cityId
     * @param areaId
     */
    @Override
    public int updateAddress(int userId, String address, int isDefault, String name, String telephone, String area, int id, String houseNumber, double ulng, double ulat, int cityId, int areaId) {
        String sql = "UPDATE `t_address` SET `user_id`=?, `name`=?, `telephone`=?, `area`=?, `address`=?,is_default=?,house_number=?,ulng=?,ulat=? ,city_id=?,area_id=? WHERE (`id`=?)";
        return update(sql, userId, name, telephone, area, address, isDefault, houseNumber, ulng, ulat, cityId, areaId, id);
    }
}